import { useEffect } from 'react'
import { BrowserRouter, Route, Routes, useRoutes } from 'react-router-dom'
import { getMenuListAction } from '@/redux/actions/global.action'
import { useDispatch } from 'react-redux'
import { Loading } from '@/components/assist'
import { useGetState } from '@/hooks/useRedux'
import { GlobalInitialState } from '@/redux/slices/global.slice'
import { RoutePathEnum } from './localRouteList'

export default function Router() {
    const dispatch = useDispatch()
    const { authRouteTreeList } = useGetState<GlobalInitialState>('global')

    useEffect(() => {
        dispatch<any>(getMenuListAction())
    }, [])

    return (
        <BrowserRouter>
            {authRouteTreeList.length ? (
                <AppRoutes />
            ) : (
                <Routes>
                    <Route path={RoutePathEnum.AnyPage} element={<Loading />} />
                </Routes>
            )}
        </BrowserRouter>
    )
}

function AppRoutes() {
    const { authRouteTreeList } = useGetState<GlobalInitialState>('global')

    return useRoutes(authRouteTreeList)
}
